package com.ansion.utils.thread;


import com.ansion.log.VLog;
import com.ansion.utils.ServerTime;
import com.ansion.utils.SettingHelper;

/**
 * Created by nuodundd on 16/4/8.
 */
public abstract class AbstractTaskThreadLimitCount extends AbstractRefreshUIThread{
    private final String TAG = this.getClass().getSimpleName();

    private static final int LOOP_COUNT_PERDAY = 200;

    private static final int TIME_INTERVAL_DAY = 1000 * 3600 * 24;

    private static final int TIME_SLEEP_HOUR = 1000 * 3600;

//    public static boolean permissionChecked = false;

    private long startTime;
    private int loopCount;
    private String key;
    private int loopCountMax = LOOP_COUNT_PERDAY;
    private int timeWaitAfterOverlimit = TIME_SLEEP_HOUR;
    private Object waitObj = new Object();
    private int timeResetLoop = TIME_INTERVAL_DAY;

    protected AbstractTaskThreadLimitCount() {
        key = this.getClass().getSimpleName();
        startTime = SettingHelper.getAbstractThreadLimitCountStartTime(key);
        loopCount = SettingHelper.getAbstractThreadLimitCountLoopCount(key);
        VLog.i(TAG,"startTime:%d,loopCount:%d",startTime,loopCount);
    }

    public int getLoopCount() {
        return loopCount;
    }

    @Override
    protected final boolean loadUIData() {
        VLog.d(TAG, "loadUIData");
        refreshLoopLimit();
        //失败次数限制
        if (loopCount > loopCountMax) {
            VLog.e(TAG, "loopCount limit sleep. loopCount ="+loopCount);
            synchronized (waitObj){
                try {
                    waitObj.wait(timeWaitAfterOverlimit);
                }catch (Exception e){
                    VLog.e(TAG, e);
                }
            }
        }
        loopCount++;
        VLog.e(TAG, "load");
        SettingHelper.setAbstractThreadLimitCountLoopCount(key, loopCount);

        return loadData();
    }

    public void refreshLoopLimit() {
        long now = ServerTime.getServerTimeMillisecond();
        if (Math.abs(now - startTime) > timeResetLoop) {
            loopCount = 0;
            startTime = now;
            SettingHelper.setAbstractThreadLimitCountStartTime(key, now);
            SettingHelper.setAbstractThreadLimitCountLoopCount(key, loopCount);
            VLog.e(TAG, "loopCount limit sleep. loopCount =" + loopCount);
        }
    }

    protected abstract boolean loadData();

    public void setLoopCountMax(int n) {
        this.loopCountMax = n;
    }

    public void setTimeWaitAfterOverlimit(int ms) {
        this.timeWaitAfterOverlimit = ms;
    }

    public  void setTimeResetLoop(int ms){
        this.timeResetLoop = ms;
    }
}
